/**
 * 
 */
package com.android.hw.projectmenu;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.text.TextUtils;
import android.util.Log;
import android.os.SystemProperties;
import com.qualcomm.qcnvitems.QcNvItems;
/**
 * @author gaoshengpan
 * 
 */
public class ShowHySoftInfo extends PreferenceActivity {
	private static final String KEY_AP_VERSION = "ap_version";
	private static final String KEY_APCOM_TIME = "apcom_time";
	private static final String KEY_BP_VERSION = "bp_version";
	private static final String KEY_BASBAND_VERSION = "baseband_version";
	private static final String KEY_KERNEL_VERSION = "kernel_version";
	private static final String KEY_HW_VERSION = "hw_version";
	private static String mUnknown = "null";
	private static String TAG = "ShowHySoftInfo";
	private static final String FILENAME_PROC_VERSION = "/proc/version";

	private QcNvItems mNv;
	/**
	 * 
	 */
	
	private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
           // TODO Auto-generated method stub
           super.handleMessage(msg);
           switch (msg.what) {

           case 0:
               
               break;
           case 1:
        	   setSummaryText(KEY_BP_VERSION, modemSN());
               break;
           default:
               break;
           }
        }
     };
	public ShowHySoftInfo() {
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.hy_soft_info);
		mNv = new QcNvItems(this);
	}

	private void setSoftwareVersion() {
		/*gaoshenpan 15-08-20 fix ap-version begin*/
		String softwareTitle = getSystemproString("ro.build.display.id");
		/*gaoshenpan 15-08-20 fix ap-version end*/
		/*gaoshenpan 15-08-20 fix ap-comptime begin*/
		String softwareTime = getSystemproString("ro.build.date");
		/*gaoshenpan 15-08-20 fix ap-comptime end*/
		Log.d(TAG, "softwareTime------->" + softwareTime);

		if (softwareTime.length() > 18) {
			int nPos = softwareTime.indexOf(".");
			nPos = softwareTime.indexOf(".", nPos);
			softwareTime = softwareTime.substring(nPos + 1);
			Log.d(TAG, "softwareTime------->1" + softwareTime);
			nPos = softwareTime.indexOf(".");
			nPos = softwareTime.indexOf(".", nPos);

			softwareTime = softwareTime.substring(nPos + 1);
			Log.d(TAG, "softwareTime------->2" + softwareTime);

			StringBuffer time = new StringBuffer(softwareTime);
			time.insert(4, '-');
			time.insert(7, '-');
			/*
			 * time.replace(10, 11, " "); time.insert(13, ':'); time.insert(16,
			 * ':');
			 */
			softwareTime = time.toString();
		}
		setSummaryText(KEY_AP_VERSION, softwareTitle);
		setSummaryText(KEY_APCOM_TIME, softwareTime);
		setInfoUseQcNVItems();
		setSummaryText(KEY_BASBAND_VERSION, getSystemproString("gsm.version.baseband"));
		setSummaryText(KEY_KERNEL_VERSION, getFormattedKernelVersion(0));
		setSummaryText(KEY_HW_VERSION, readFile("/sys/devices/soc0/hw_pcbboard_version"));

	}
	private void setInfoUseQcNVItems(){
        if (mNv == null) {
            mNv = new QcNvItems(this);
        }
        if(mNv != null){
         Log.d(TAG, "send message -----:"+"hh");
         mHandler.sendEmptyMessage(1);
         }
    }
	
	 private String modemSN() {
	        String sn = null;
	        if (mNv == null) {
	            mNv = new QcNvItems(this);
	        }
	        if(mNv != null){
	        try {
	        	/*15-09-01 gaoshenpan  fix modem_number begin */
	            sn = mNv.getSNNumber().substring(32);
	            /*15-09-01 gaoshenpan  fix modem_number end */
	            Log.d(TAG, "readSN -----:" + sn);
	        } catch (Exception e) {
	            // TODO: handle exception
	            Log.e(TAG, "getSN e:" + e);
	        }
	        Log.e(TAG, "getSN info :" + sn);
	          }
	        return sn;
	    }
	 private static String getFormattedKernelVersion(int i) {
	        try {
	            Log.d(TAG,"getFormattedKernelVersion----11111----->"+formatKernelVersion(readLine(FILENAME_PROC_VERSION),0));
	            return formatKernelVersion(readLine(FILENAME_PROC_VERSION),i);

	        } catch (IOException e) {
	            Log.e(TAG,
	                "IO Exception when getting kernel version for Device Info screen",
	                e);

	            return "Unavailable";
	        }
	    }
	 
	 public static String formatKernelVersion(String rawKernelVersion,int i) {
	        // Example (see tests for more):
	        // Linux version 3.0.31-g6fb96c9 (android-build@xxx.xxx.xxx.xxx.com) \
	        //     (gcc version 4.6.x-xxx 20120106 (prerelease) (GCC) ) #1 SMP PREEMPT \
	        //     Thu Jun 28 11:02:39 PDT 2012

	        final String PROC_VERSION_REGEX =
	            "Linux version (\\S+) " + /* group 1: "3.0.31-g6fb96c9" */
	            "\\((\\S+?)\\) " +        /* group 2: "x@y.com" (kernel builder) */
	            "(?:\\(gcc.+? \\)) " +    /* ignore: GCC version information */
	            "(#\\d+) " +              /* group 3: "#1" */
	            "(?:.*?)?" +              /* ignore: optional SMP, PREEMPT, and any CONFIG_FLAGS */
	            "((Sun|Mon|Tue|Wed|Thu|Fri|Sat).+)"; /* group 4: "Thu Jun 28 11:02:39 PDT 2012" */
	        Log.d(TAG,"--->"+rawKernelVersion);
	    	Log.d(TAG,Pattern.compile(PROC_VERSION_REGEX).toString());
	        Matcher m = Pattern.compile(PROC_VERSION_REGEX).matcher(rawKernelVersion);
	        if (!m.matches()) {
	            Log.e(TAG, "Regex did not match on /proc/version: " + rawKernelVersion);
	            return "Unavailable";
	        } else if (m.groupCount() < 4) {
	            Log.e(TAG, "Regex match on /proc/version only returned " + m.groupCount()
	                    + " groups");
	            return "Unavailable";
	        }

	        if (i==0) {
	        	 return m.group(1);
	        } else {
	            /*return m.group(1) + "\n" +                 // 3.0.31-g6fb96c9
	                m.group(2) + " " + m.group(3) + "\n" + // x@y.com #1
	                m.group(4);    */                        // Thu Jun 28 11:02:39 PDT 2012
	        	return m.group(4);
	        }
	    }


	 private static String readLine(String filename) throws IOException {
	        BufferedReader reader = new BufferedReader(new FileReader(filename), 256);
	        try {
//	            Log.d(TAG,"readLine--------->"+reader.readLine());
	            String version = reader.readLine();
	            return version;
	        } finally {
	            reader.close();
	        }
	    }
	public static String readFile(String filePath) {
		String res = "";
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(new File(filePath))));
			String str = null;
			while ((str = br.readLine()) != null) {
				res += str;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	private static String getSystemproString(String property) {
		return SystemProperties.get(property, "unknown");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setSoftwareVersion();
	}

	private void setSummaryText(String preferenceKey, String value) {
		Preference preference = findPreference(preferenceKey);
		if (preference == null)
			return;

		if (TextUtils.isEmpty(value))
			preference.setSummary(mUnknown);
		else
			preference.setSummary(value);
	}
	
	/* (non-Javadoc)
     * @see android.preference.PreferenceActivity#onDestroy()
     */
    @Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mNv != null) {
			mNv.dispose();
		}
	}
}
